package com.rex.saas.job;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.rex.saas.bean.DeviceBasicData;
import com.rex.saas.constants.Constants;
import com.rex.saas.db.entity.*;
import com.rex.saas.db.mapper.SaasDeviceStatisticsMapper;
import com.rex.saas.db.mapper.SaasSpaceStatisticsMapper;
import com.rex.saas.enums.SpaceTypeEnum;
import com.rex.saas.service.DeviceService;
import com.rex.saas.service.RexolarApiClient;
import com.rex.saas.service.SpaceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Component
@Slf4j
public class StatisticsJob {
    @Autowired
    private SaasDeviceStatisticsMapper saasDeviceStatisticsMapper;

    @Autowired
    private SaasSpaceStatisticsMapper saasSpaceStatisticsMapper;

    @Autowired
    private DeviceService deviceService;

    @Autowired
    private SpaceService spaceService;

    @Autowired
    private RexolarApiClient rexolarApiClient;

//    @Scheduled(cron = "0 0 0 * * ?") // 每
    @Scheduled(cron = "0 1/10 * * * ?") // 每
    public void syncSpaceStatistics() throws Exception{
        List<SaasSpaceInfo> list =spaceService.getAllList();
        list.forEach(spaceInfo -> {
            String tenantToken = rexolarApiClient.getTenantToken(spaceInfo.getTenantId());
            if(StringUtils.isEmpty(tenantToken)){
                log.error("syncSpaceStatistics getTenantToken error, tenantId:{}", spaceInfo.getTenantId());
                return;
            }
            List<SaasSpaceDeviceRelation> spaceDeviceRelations = spaceService.getCustomerDeviceList(spaceInfo.getId(), spaceInfo.getCustomerId());
            if(CollectionUtils.isEmpty(spaceDeviceRelations)){
                return;
            }
            if(SpaceTypeEnum.POWER_MONITORING.getCode().equals(spaceInfo.getType())){
                powerMonitoringStatistics(spaceDeviceRelations, tenantToken, spaceInfo);
            }else if(SpaceTypeEnum.SOCKET_MONITORING.getCode().equals(spaceInfo.getType())){
                socketMonitoringStatistics(spaceDeviceRelations, tenantToken, spaceInfo);
            }
        });
        log.info("syncSpaceStatistics end, time：{}", new Date());
    }

    private void socketMonitoringStatistics(List<SaasSpaceDeviceRelation> spaceDeviceRelations, String tenantToken, SaasSpaceInfo spaceInfo) {
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        long startTime = startOfYesterday.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long endTime = endOfYesterday.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String yesterdayStr = yesterday.toString();
        float pCeeTotal = 0f;
        float pCeiTotal = 0f;
        float gCeeTotal = 0f;
        float gCeiTotal = 0f;
        for (SaasSpaceDeviceRelation saasSpaceDeviceRelation : spaceDeviceRelations){
            DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(saasSpaceDeviceRelation.getDeviceName(), tenantToken);
            if(deviceBasicData==null){
                log.error("socketMonitoringStatistics getDeviceByDeviceName error, saasSpaceDeviceRelation:{}", saasSpaceDeviceRelation);
                return;
            }
            if(saasSpaceDeviceRelation.getType() != Constants.CT_SOCKET){
                log.info("socketMonitoringStatistics saasSpaceDeviceRelation.type != Constants.CT_SOCKET, deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
                return;
            }
            if(endTime < saasSpaceDeviceRelation.getGmtCreated().getTime()){
                log.error("socketMonitoringStatistics endTime < saasDeviceInfo.gmtModified today binded, deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
                continue;
            }
            long start = startTime;
            if(start < saasSpaceDeviceRelation.getGmtCreated().getTime()){
                start  = saasSpaceDeviceRelation.getGmtCreated().getTime();
            }
            float ceiTotal = 0f;
            Map<String, Object> tmp = rexolarApiClient.getDeviceTimeSeries(
                    deviceBasicData.getCoreId(), tenantToken,
                    new String[]{Constants.CEI_1},
                    start, endTime,
                    100000, false, 300000L, "AVG", false
            );
            if(CollectionUtils.isEmpty(tmp)){
                log.error("socketMonitoringStatistics getDeviceTimeSeries is empty, saasSpaceDeviceRelation.getDeviceName:{}", saasSpaceDeviceRelation.getDeviceName());
            }else {
                List<Map> ceiList = (List<Map>) tmp.get(Constants.CEI_1);
                if(!CollectionUtils.isEmpty(ceiList)){
                    ceiTotal = Float.valueOf(ceiList.get(ceiList.size()-1).get("value").toString())
                            - Float.valueOf(ceiList.get(0).get("value").toString());
                }
                saveDeviceStatistics(saasSpaceDeviceRelation, spaceInfo, ceiTotal, 0, yesterdayStr);
                gCeiTotal += ceiTotal;
            }
        }
        saveStatistics(spaceInfo, yesterdayStr, pCeeTotal, pCeiTotal, gCeeTotal, gCeiTotal);
    }

    private void saveStatistics(SaasSpaceInfo spaceInfo, String yesterdayStr, float pCeeTotal, float pCeiTotal, float gCeeTotal, float gCeiTotal) {
        LocalDate yesterday = LocalDate.parse(yesterdayStr);
        List<SaasSpaceStatistics> dayList = saasSpaceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasSpaceStatistics>()
                .eq(SaasSpaceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasSpaceStatistics::getRecordType, Constants.STATISTICS_DAY)
                .ge(SaasSpaceStatistics::getRecordDate, yesterdayStr)
        );

        if(CollectionUtils.isEmpty(dayList)){
            SaasSpaceStatistics dayStatistics = new SaasSpaceStatistics();
            dayStatistics.setSpaceId(spaceInfo.getId());
            dayStatistics.setRecordType(Constants.STATISTICS_DAY);
            dayStatistics.setRecordDate(yesterdayStr);
            dayStatistics.setGCeiTotal(gCeiTotal);
            dayStatistics.setGCeeTotal(gCeeTotal);
            dayStatistics.setPCeeTotal(pCeeTotal);
            dayStatistics.setPCeiTotal(pCeiTotal);
            if(saasSpaceStatisticsMapper.insert(dayStatistics)!=1) {
                log.error("saveStatistics insert day statistics end, dayStatistics:{}", dayStatistics);
            }else {
                log.info("saveStatistics insert day statistics end, dayStatistics:{}", dayStatistics);
            }
        }else {
            SaasSpaceStatistics dayStatistics = dayList.get(0);
            dayStatistics.setGCeiTotal(gCeiTotal);
            dayStatistics.setGCeeTotal(gCeeTotal);
            dayStatistics.setPCeeTotal(pCeeTotal);
            dayStatistics.setPCeiTotal(pCeiTotal);
            dayStatistics.setGmtModified(new Date());
            if(saasSpaceStatisticsMapper.updateById(dayStatistics)!=1) {
                log.error("saveStatistics update day statistics end, dayStatistics:{}", dayStatistics);
            }else {
                log.info("saveStatistics update day statistics end, dayStatistics:{}", dayStatistics);
            }
        }

        String recordMonth = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        List<SaasSpaceStatistics> dayLists = saasSpaceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasSpaceStatistics>()
                .eq(SaasSpaceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasSpaceStatistics::getRecordType, Constants.STATISTICS_DAY)
                .ge(SaasSpaceStatistics::getRecordDate, recordMonth+"-01")
                .le(SaasSpaceStatistics::getRecordDate, recordMonth+"-31")
        );
        float monthPCeeTotal = 0f;
        float monthPCeiTotal = 0f;
        float monthGCeeTotal = 0f;
        float monthGCeiTotal = 0f;
        for(SaasSpaceStatistics dayStatistics : dayLists){
            monthPCeeTotal += dayStatistics.getPCeeTotal();
            monthPCeiTotal += dayStatistics.getPCeiTotal();
            monthGCeeTotal += dayStatistics.getGCeeTotal();
            monthGCeiTotal += dayStatistics.getGCeiTotal();
        }

        List<SaasSpaceStatistics> month = saasSpaceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasSpaceStatistics>()
                .eq(SaasSpaceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasSpaceStatistics::getRecordType, Constants.STATISTICS_MONTH)
                .ge(SaasSpaceStatistics::getRecordDate, recordMonth)
        );
        if(CollectionUtils.isEmpty(month)){
            SaasSpaceStatistics monthStatistics = new SaasSpaceStatistics();
            monthStatistics.setSpaceId(spaceInfo.getId());
            monthStatistics.setRecordType(Constants.STATISTICS_MONTH);
            monthStatistics.setRecordDate(recordMonth);
            monthStatistics.setGCeiTotal(monthGCeiTotal);
            monthStatistics.setGCeeTotal(monthGCeeTotal);
            monthStatistics.setPCeeTotal(monthPCeeTotal);
            monthStatistics.setPCeiTotal(monthPCeiTotal);
            if(saasSpaceStatisticsMapper.insert(monthStatistics)!=1){
                log.error("saveStatistics insert month statistics end, monthStatistics:{}", monthStatistics);
            }
        }else {
            SaasSpaceStatistics monthStatistics = month.get(0);
            monthStatistics.setGCeiTotal(monthGCeiTotal);
            monthStatistics.setGCeeTotal(monthGCeeTotal);
            monthStatistics.setPCeeTotal(monthPCeeTotal);
            monthStatistics.setPCeiTotal(monthPCeiTotal);
            monthStatistics.setGmtModified(new Date());
            if(saasSpaceStatisticsMapper.updateById(monthStatistics)!=1){
                log.error("saveStatistics update month statistics end, monthStatistics:{}", monthStatistics);
            }
        }

        String recordYear = yesterday.format(DateTimeFormatter.ofPattern("yyyy"));
        List<SaasSpaceStatistics> monthLists = saasSpaceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasSpaceStatistics>()
                .eq(SaasSpaceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasSpaceStatistics::getRecordType, Constants.STATISTICS_MONTH)
                .ge(SaasSpaceStatistics::getRecordDate, recordYear+"-01")
                .le(SaasSpaceStatistics::getRecordDate, recordYear+"-12")
        );
        float yearPCeeTotal = 0f;
        float yearPCeiTotal = 0f;
        float yearGCeeTotal = 0f;
        float yearGCeiTotal = 0f;
        for(SaasSpaceStatistics monthStatistics : monthLists){
            yearPCeeTotal += monthStatistics.getPCeeTotal();
            yearPCeiTotal += monthStatistics.getPCeiTotal();
            yearGCeeTotal += monthStatistics.getGCeeTotal();
            yearGCeiTotal += monthStatistics.getGCeiTotal();
        }
        List<SaasSpaceStatistics> years = saasSpaceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasSpaceStatistics>()
                .eq(SaasSpaceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasSpaceStatistics::getRecordType, Constants.STATISTICS_YEAR)
                .eq(SaasSpaceStatistics::getRecordDate, recordYear)
        );
        if(CollectionUtils.isEmpty(years)){
            SaasSpaceStatistics yearStatistics = new SaasSpaceStatistics();
            yearStatistics.setSpaceId(spaceInfo.getId());
            yearStatistics.setRecordType(Constants.STATISTICS_YEAR);
            yearStatistics.setRecordDate(recordYear);
            yearStatistics.setGCeiTotal(yearGCeiTotal);
            yearStatistics.setGCeeTotal(yearGCeeTotal);
            yearStatistics.setPCeeTotal(yearPCeeTotal);
            yearStatistics.setPCeiTotal(yearPCeiTotal);
            if(saasSpaceStatisticsMapper.insert(yearStatistics)!=1){
                log.info("saveStatistics insert year statistics end, yearStatistics:{}", yearStatistics);
            }
        }else {
            SaasSpaceStatistics yearStatistics = years.get(0);
            yearStatistics.setGCeiTotal(yearGCeiTotal);
            yearStatistics.setGCeeTotal(yearGCeeTotal);
            yearStatistics.setPCeeTotal(yearPCeeTotal);
            yearStatistics.setPCeiTotal(yearPCeiTotal);
            yearStatistics.setGmtModified(new Date());
            if(saasSpaceStatisticsMapper.updateById(yearStatistics)!=1){
                log.info("saveStatistics update year statistics end, yearStatistics:{}", yearStatistics);
            }
        }
    }

    private void powerMonitoringStatistics(List<SaasSpaceDeviceRelation> spaceDeviceRelations, String tenantToken, SaasSpaceInfo spaceInfo) {
        LocalDate today = LocalDate.now();
        LocalDate yesterday = today.minusDays(1);
        LocalDateTime startOfYesterday = yesterday.atStartOfDay();
        LocalDateTime endOfYesterday = yesterday.atTime(23, 59, 59);
        long startTime = startOfYesterday.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        long endTime = endOfYesterday.toInstant(ZoneOffset.of("+8")).toEpochMilli();
        String yesterdayStr = yesterday.toString();
        float pCeeTotal = 0f;
        float pCeiTotal = 0f;
        float gCeeTotal = 0f;
        float gCeiTotal = 0f;
        for (SaasSpaceDeviceRelation saasSpaceDeviceRelation : spaceDeviceRelations){
            DeviceBasicData deviceBasicData = rexolarApiClient.getDeviceByDeviceName(saasSpaceDeviceRelation.getDeviceName(), tenantToken);
            if(deviceBasicData==null){
                log.error("powerMonitoringStatistics getDeviceByDeviceName error, saasSpaceDeviceRelation.deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
                return;
            }
            if(saasSpaceDeviceRelation.getType()!= Constants.CT_IN && saasSpaceDeviceRelation.getType()!= Constants.CT_OUT){
                log.error("powerMonitoringStatistics saasSpaceDeviceRelation.type error, saasSpaceDeviceRelation:{}", saasSpaceDeviceRelation);
                continue;
            }
            if(endTime < saasSpaceDeviceRelation.getGmtCreated().getTime()){
                log.error("powerMonitoringStatistics endTime < saasDeviceInfo.gmtModified today binded, saasSpaceDeviceRelation.deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
                continue;
            }
            long start = startTime;
            if(start < saasSpaceDeviceRelation.getGmtCreated().getTime()){
                start  = saasSpaceDeviceRelation.getGmtCreated().getTime();
            }
            float tmpCei = 0f;
            float tmpCee = 0f;
            Map<String, Object> tmp = rexolarApiClient.getDeviceTimeSeries(
                    deviceBasicData.getCoreId(), tenantToken,
                    new String[]{Constants.TotalCEI_1, Constants.TotalCEE_1,Constants.TotalActivePower_1},
                    start, endTime,
                    100000, false, 300000L, "AVG", false
            );
            if(CollectionUtils.isEmpty(tmp)){
                log.error("powerMonitoringStatistics getDeviceTimeSeries is empty, saasSpaceDeviceRelation.deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
            }else {
                List<Map> ceiList = (List<Map>) tmp.get(Constants.TotalCEI_1);
                if(!CollectionUtils.isEmpty(ceiList)){
                    tmpCei = Float.valueOf(ceiList.get(ceiList.size()-1).get("value").toString())
                            - Float.valueOf(ceiList.get(0).get("value").toString());
                }
                List<Map> ceeList = (List<Map>) tmp.get(Constants.TotalCEE_1);
                if(!CollectionUtils.isEmpty(ceeList)){
                    tmpCee = Float.valueOf(ceeList.get(ceiList.size()-1).get("value").toString())
                            - Float.valueOf(ceeList.get(0).get("value").toString());
                }

                if(saasSpaceDeviceRelation.getType()==Constants.CT_IN){
                    gCeiTotal  += tmpCei;
                    gCeeTotal  += tmpCee;
                }else if(saasSpaceDeviceRelation.getType()==Constants.CT_OUT){
                    pCeiTotal  += tmpCei;
                    pCeeTotal  += tmpCee;
                }else{
                    log.error("powerMonitoringStatistics device type error, saasSpaceDeviceRelation.deviceName:{}", saasSpaceDeviceRelation.getDeviceName());
                }
                saveDeviceStatistics(saasSpaceDeviceRelation, spaceInfo, tmpCei, tmpCee, yesterdayStr);
            }
        }
        saveStatistics(spaceInfo, yesterdayStr, pCeeTotal, pCeiTotal, gCeeTotal, gCeiTotal);

    }

    private void saveDeviceStatistics(SaasSpaceDeviceRelation saasSpaceDeviceRelation, SaasSpaceInfo spaceInfo, float tmpCei, float tmpCee, String yesterdayStr) {
        List<SaasDeviceStatistics> dayList = saasDeviceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasDeviceStatistics>()
                .eq(SaasDeviceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasDeviceStatistics::getDeviceName, saasSpaceDeviceRelation.getDeviceName())
                .eq(SaasDeviceStatistics::getRecordType, Constants.STATISTICS_DAY)
                .ge(SaasDeviceStatistics::getRecordDate, yesterdayStr)
        );

        if(CollectionUtils.isEmpty(dayList)){
            SaasDeviceStatistics dayStatistics = new SaasDeviceStatistics();
            dayStatistics.setSpaceId(spaceInfo.getId());
            dayStatistics.setRecordType(Constants.STATISTICS_DAY);
            dayStatistics.setRecordDate(yesterdayStr);
            dayStatistics.setTotalCee(tmpCee);
            dayStatistics.setTotalCei(tmpCei);
            dayStatistics.setDeviceName(saasSpaceDeviceRelation.getDeviceName());
            dayStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            dayStatistics.setTenantId(spaceInfo.getTenantId());
            dayStatistics.setCustomerId(spaceInfo.getCustomerId());
            dayStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            if(saasDeviceStatisticsMapper.insert(dayStatistics)!=1) {
                log.error("saveDeviceStatistics insert day statistics end, dayStatistics:{}", dayStatistics);
            }else {
                log.info("saveDeviceStatistics insert day statistics end, dayStatistics:{}", dayStatistics);
            }
        }else {
            SaasDeviceStatistics dayStatistics = dayList.get(0);
            dayStatistics.setTotalCee(tmpCee);
            dayStatistics.setTotalCei(tmpCei);
            dayStatistics.setGmtModified(new Date());
            if(saasDeviceStatisticsMapper.updateById(dayStatistics)!=1) {
                log.error("saveDeviceStatistics update day statistics end, dayStatistics:{}", dayStatistics);
            }else {
                log.info("saveDeviceStatistics update day statistics end, dayStatistics:{}", dayStatistics);
            }
        }

        LocalDate yesterday = LocalDate.parse(yesterdayStr);
        String recordMonth = yesterday.format(DateTimeFormatter.ofPattern("yyyy-MM"));
        List<SaasDeviceStatistics> dayLists = saasDeviceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasDeviceStatistics>()
                .eq(SaasDeviceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasDeviceStatistics::getDeviceName, saasSpaceDeviceRelation.getDeviceName())
                .eq(SaasDeviceStatistics::getRecordType, Constants.STATISTICS_DAY)
                .ge(SaasDeviceStatistics::getRecordDate, recordMonth+"-01")
                .le(SaasDeviceStatistics::getRecordDate, recordMonth+"-31")
        );
        float monthGCeeTotal = 0f;
        float monthGCeiTotal = 0f;
        for(SaasDeviceStatistics dayStatistics : dayLists){
            monthGCeeTotal += dayStatistics.getTotalCee();
            monthGCeiTotal += dayStatistics.getTotalCei();
        }

        List<SaasDeviceStatistics> month = saasDeviceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasDeviceStatistics>()
                .eq(SaasDeviceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasDeviceStatistics::getDeviceName, saasSpaceDeviceRelation.getDeviceName())
                .eq(SaasDeviceStatistics::getRecordType, Constants.STATISTICS_MONTH)
                .ge(SaasDeviceStatistics::getRecordDate, recordMonth)
        );
        if(CollectionUtils.isEmpty(month)){
            SaasDeviceStatistics monthStatistics = new SaasDeviceStatistics();
            monthStatistics.setSpaceId(spaceInfo.getId());
            monthStatistics.setRecordType(Constants.STATISTICS_MONTH);
            monthStatistics.setRecordDate(recordMonth);
            monthStatistics.setTotalCee(monthGCeeTotal);
            monthStatistics.setTotalCei(monthGCeiTotal);
            monthStatistics.setDeviceName(saasSpaceDeviceRelation.getDeviceName());
            monthStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            monthStatistics.setTenantId(spaceInfo.getTenantId());
            monthStatistics.setCustomerId(spaceInfo.getCustomerId());
            monthStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            if(saasDeviceStatisticsMapper.insert(monthStatistics)!=1){
                log.error("saveDeviceStatistics insert month statistics end, monthStatistics:{}", monthStatistics);
            }
        }else {
            SaasDeviceStatistics monthStatistics = month.get(0);
            monthStatistics.setTotalCee(monthGCeeTotal);
            monthStatistics.setTotalCei(monthGCeiTotal);
            monthStatistics.setGmtModified(new Date());
            if(saasDeviceStatisticsMapper.updateById(monthStatistics)!=1){
                log.error("saveDeviceStatistics update month statistics end, monthStatistics:{}", monthStatistics);
            }
        }

        String recordYear = yesterday.format(DateTimeFormatter.ofPattern("yyyy"));
        List<SaasDeviceStatistics> monthLists = saasDeviceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasDeviceStatistics>()
                .eq(SaasDeviceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasDeviceStatistics::getRecordType, Constants.STATISTICS_MONTH)
                .eq(SaasDeviceStatistics::getDeviceName, saasSpaceDeviceRelation.getDeviceName())
                .ge(SaasDeviceStatistics::getRecordDate, recordYear+"-01")
                .le(SaasDeviceStatistics::getRecordDate, recordYear+"-12")
        );
        float yearGCeeTotal = 0f;
        float yearGCeiTotal = 0f;
        for(SaasDeviceStatistics monthStatistics : monthLists){
            yearGCeeTotal += monthStatistics.getTotalCee();
            yearGCeiTotal += monthStatistics.getTotalCei();
        }
        List<SaasDeviceStatistics> years = saasDeviceStatisticsMapper.selectList(new LambdaQueryWrapper<SaasDeviceStatistics>()
                .eq(SaasDeviceStatistics::getSpaceId, spaceInfo.getId())
                .eq(SaasDeviceStatistics::getDeviceName, saasSpaceDeviceRelation.getDeviceName())
                .eq(SaasDeviceStatistics::getRecordType, Constants.STATISTICS_YEAR)
                .eq(SaasDeviceStatistics::getRecordDate, recordYear)
        );
        if(CollectionUtils.isEmpty(years)){
            SaasDeviceStatistics yearStatistics = new SaasDeviceStatistics();
            yearStatistics.setSpaceId(spaceInfo.getId());
            yearStatistics.setRecordType(Constants.STATISTICS_YEAR);
            yearStatistics.setRecordDate(recordYear);
            yearStatistics.setTotalCee(monthGCeeTotal);
            yearStatistics.setTotalCei(monthGCeiTotal);
            yearStatistics.setDeviceName(saasSpaceDeviceRelation.getDeviceName());
            yearStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            yearStatistics.setTenantId(spaceInfo.getTenantId());
            yearStatistics.setCustomerId(spaceInfo.getCustomerId());
            yearStatistics.setDeviceType(saasSpaceDeviceRelation.getType());
            if(saasDeviceStatisticsMapper.insert(yearStatistics)!=1){
                log.info("saveDeviceStatistics insert year statistics end, yearStatistics:{}", yearStatistics);
            }
        }else {
            SaasDeviceStatistics yearStatistics = years.get(0);
            yearStatistics.setTotalCei(yearGCeiTotal);
            yearStatistics.setTotalCee(yearGCeeTotal);
            yearStatistics.setGmtModified(new Date());
            if(saasDeviceStatisticsMapper.updateById(yearStatistics)!=1){
                log.info("saveDeviceStatistics update year statistics end, yearStatistics:{}", yearStatistics);
            }
        }
    }
}